package Io.nio;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class NioClient {
    public static void main(String[] args) {
        try (SocketChannel socketChannel = SocketChannel.open()) {
            // 连接服务器
            socketChannel.connect(new InetSocketAddress("localhost", 8082));
            socketChannel.configureBlocking(false);

            // 发送数据到服务器
            String message = "Hello, NIO Server!，我是客户端1号";
            ByteBuffer writeBuffer = ByteBuffer.wrap(message.getBytes());
            socketChannel.write(writeBuffer);

            // 接收服务器响应
            ByteBuffer readBuffer = ByteBuffer.allocate(1024);
            while (true) {
                int bytesRead = socketChannel.read(readBuffer);
                if (bytesRead > 0) {
                    readBuffer.flip();
                    byte[] data = new byte[readBuffer.remaining()];
                    readBuffer.get(data);
                    String response = new String(data);
                    System.out.println("收到响应: " + response);
                    break;  // 收到响应后退出循环
                } else if (bytesRead == -1) {
                    // 服务器关闭连接
                    System.out.println("服务器断开连接");
                    break;  // 服务器断开连接后退出循环
                } else if (bytesRead == 0) {
                    // 没有数据可读，继续循环
                    Thread.sleep(100);  // 等待一段时间再尝试读取
                }
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
